<template>
  <basic-container class="templateUi">
    <el-card class="box-card">
      <div class="designer-btns">
        <!-- 画布上部分操作栏 -->
        <div class="pull-left">
          <ul class="">
            <li @click="showPreviewModal()">
              <img src="@/assets/img/station-ui/预览.png" alt="" />
              <p>预览</p>
            </li>
          </ul>
        </div>
        <div class="pull-right">
          <div class="split-line"></div>
          <ul>
            <li @click="onReturn()">
              <img src="@/assets/img/station-ui/返回.png" alt="" />
              <p>返回</p>
            </li>
            <li class="bg-blue" @click="onSubmit()">
              <el-button type="primary" icon="el-icon-document">
                <p style="margin-top: 10px">保存</p>
              </el-button>
            </li>
          </ul>
        </div>
      </div>
      <div class="designer-description">
        <div>模版名称: {{ templateInfo.zhCnName }}</div>
      </div>
      <!-- 画布空间 -->
      <el-row :gutter="5" class="designer-box">
        <!-- 画布内容 -->
        <el-col :span="19">
          <el-card class="designer-div">
            <table border="1" cellpadding="0" cellspacing="0" class="table-report">
              <tbody>
                <tr>
                  <td colspan="6" style="font-size: 27px; line-height: 45px">XX有限公司</td>
                </tr>
                <tr>
                  <td colspan="6" style="font-size: 20px; line-height: 32px">XX测试报告</td>
                </tr>
                <tr>
                  <td>产品型号：</td>
                  <td data-name="partSpecifications"></td>
                  <td>检验日期：</td>
                  <td style="width: 300px" data-name="examinedDate"></td>
                  <td>湿度：</td>
                  <td data-name="humidity"></td>
                </tr>
                <tr>
                  <td>出厂编号：</td>
                  <td data-name="factoryCode"></td>
                  <td>测试人员：</td>
                  <td data-name="examinedBy"></td>
                  <td>品质确认：</td>
                  <td data-name="qualityConfirmation"></td>
                </tr>
                <tr>
                  <td colspan="4"></td>
                  <td>判定</td>
                  <td data-name="examinedResult"></td>
                </tr>
                <tr data-name="attributes">
                  <td data-name="sequence" style="width: 140px">序号</td>
                  <td data-name="type">检验项目</td>
                  <td data-name="zhCnName" colspan="2">检验标准</td>
                  <td data-name="checkValue">检验结果</td>
                  <td data-name="zhCnContent">备注</td>
                </tr>
              </tbody>
            </table>
          </el-card>
        </el-col>
        <el-col :span="5" class="attr-div">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>工站基本信息</span>
            </div>
            <el-tabs class="nav-tab" v-model="activeName" @tab-click="turnToInputNameClick()">
              <el-tab-pane label="基本信息" name="basicInfoConfig">
                <el-form :model="model" label-width="110px" label-position="top">
                  <el-form-item label="单元格字段:">
                    <el-input name="tdName" v-model="model.tdName" @blur="tableTdNameKeyUpFunction()" :clearable="true"></el-input>
                  </el-form-item>
                  <el-form-item label="单元格宽度:">
                    <el-input-number name="tdWidth" v-model="model.tdWidth" @blur="tableTdWidthKeyUpFunction()" :clearable="true" controls-position="right"></el-input-number>
                  </el-form-item>
                  <el-form-item label="单元格行高度:">
                    <el-input-number
                      name="tdLineHeight"
                      v-model="model.tdLineHeight"
                      @blur="tableTdLineHeightKeyUpFunction()"
                      :clearable="true"
                      controls-position="right"
                      :min="12"
                    ></el-input-number>
                  </el-form-item>
                  <el-form-item label="单元格字体大小:">
                    <el-input-number
                      name="tdFontSize"
                      v-model="model.tdFontSize"
                      @blur="tableTdFontSizeKeyUpFunction()"
                      :clearable="true"
                      controls-position="right"
                      :min="12"
                    ></el-input-number>
                  </el-form-item>
                  <el-form-item label="跨行数:">
                    <el-input-number
                      name="rowspanLenth"
                      v-model="model.rowspanLenth"
                      @blur="tableTdRowSpanLenthKeyUpFunction('rowspanLenth')"
                      :clearable="true"
                      controls-position="right"
                      :min="1"
                    ></el-input-number>
                  </el-form-item>
                  <el-form-item label="跨列数:">
                    <el-input-number
                      name="colspanLenth"
                      v-model="model.colspanLenth"
                      @blur="tableTdRowSpanLenthKeyUpFunction('colspanLenth')"
                      :clearable="true"
                      controls-position="right"
                      :min="1"
                    ></el-input-number>
                  </el-form-item>
                  <el-form-item label="表格行操作:">
                    <el-button style="width: 48%" type="primary" size="small" @click="addReportTr()">插入下一行</el-button>
                    <el-button style="width: 48%" type="primary" size="small" @click="deleteReportTr()">删除当前行</el-button>
                  </el-form-item>
                  <el-form-item label="表格列操作(仅操作最后一列):">
                    <el-button style="width: 48%" type="primary" size="small" @click="addReportTd()">插入表格列</el-button>
                    <el-button style="width: 48%" type="primary" size="small" @click="deleteReportTd()">删除表格列</el-button>
                  </el-form-item>
                </el-form>
              </el-tab-pane>
            </el-tabs>
          </el-card>
        </el-col>
      </el-row>
    </el-card>
  </basic-container>
</template>
<script>
export default {
  data() {
    return {
      templateInfo: '',
      activeName: 'basicInfoConfig',
      model: {}
    };
  },
  mounted() {
    /**
     * 检验报告中td点击事件
     */
    $('.designer-box .designer-div').on('click', '.table-report td', (event) => {
      let tagName = $(event.target).get(0).tagName;
      $('.table-report').find('td').removeClass('tdActive');
      let $currentDom = $(event.target);
      if (tagName !== 'TD') {
        $currentDom = $(event.target).parents('td');
      }
      $currentDom.addClass('tdActive');
      this.model.rowspanLenth = $currentDom.attr('rowspan') ? $currentDom.attr('rowspan') : 1;
      this.model.colspanLenth = $currentDom.attr('colspan') ? $currentDom.attr('colspan') : 1;
      let tdFontSize = $currentDom.css('font-size');
      if (tdFontSize) {
        this.model.tdFontSize = tdFontSize.substr(0, tdFontSize.length - 2);
      } else {
        this.model.tdFontSize = '';
      }

      let tdLineHeight = $currentDom.css('line-height');
      if (tdLineHeight) {
        this.model.tdLineHeight = tdLineHeight.substr(0, tdLineHeight.length - 2);
      } else {
        this.model.tdLineHeight = '';
      }

      let tdWidth = $currentDom.css('width');
      if (tdWidth) {
        this.model.tdWidth = tdWidth.substr(0, tdWidth.length - 2);
      } else {
        this.model.tdWidth = '';
      }

      this.model.tdName = $currentDom.attr('data-name') ? $currentDom.attr('data-name') : '';
      this.model.trName = $currentDom.parents('tr').attr('data-name') ? $currentDom.parents('tr').attr('data-name') : '';
    });

    /**
     * 检验报告中td双击事件
     */
    $('.designer-box .designer-div').dblclick((event) => {
      let tagName = $(event.target).get(0).tagName;
      if (tagName === 'TD') {
        //将TD中的值放置输入框中进行修改
        let tdVal = $(event.target).text();
        $(event.target).html('');
        $(event.target).append(`<input class="input-control" type="text" autocomplete="off" value=${tdVal}>`);
        setTimeout(() => {
          $(event.target).find('.input-control').select();
        }, 80);
      } else if (tagName === 'INPUT') {
        let inputVal = $(event.target).val();
        $(event.target).parents('td').html(inputVal);
      }
    });

    /**
     * 检验报告中输入框回车事件
     */
    $('.designer-box .designer-div').keypress((event) => {
      let isInputControl = $(event.target).hasClass('input-control');
      if (isInputControl && event.keyCode === 13) {
        let inputVal = $(event.target).val();
        $(event.target).parents('td').html(inputVal);
      }
    });
  },
  methods: {
    /**
     * 表格TD字段名称修改
     */
    tableTdNameKeyUpFunction() {
      let $tdActive = $('.table-report').find('td.tdActive');
      $tdActive.attr('data-name', this.model.tdName);
    },

    /**
     * 表格TR字段名称修改
     */
    tableTrNameKeyUpFunction() {
      let $trActive = $('.table-report').find('td.tdActive').parents('tr');
      $trActive.attr('data-name', this.model.trName);
    },

    /**
     * 检验报告单元格宽度调整
     */
    tableTdWidthKeyUpFunction() {
      let $tdActive = $('.table-report').find('td.tdActive');
      $tdActive.css('width', this.model.tdWidth + 'px');
    },

    /**
     * 检验报告单元格行高调整
     */
    tableTdLineHeightKeyUpFunction() {
      let $tdActive = $('.table-report').find('td.tdActive');
      $tdActive.css('line-height', this.model.tdLineHeight + 'px');
    },

    /**
     * 检验报告单元格字体调整
     */
    tableTdFontSizeKeyUpFunction() {
      let $tdActive = $('.table-report').find('td.tdActive');
      $tdActive.css('font-size', this.model.tdFontSize + 'px');
    },

    /**
     * 检验报告单元格跨行调整
     */
    tableTdRowSpanLenthKeyUpFunction(name) {
      //当前选中单元格
      let $tdActive = $('.table-report').find('td.tdActive');
      //当前选中单元格索引
      let tdActiveIndex = $tdActive.index();
      //当前选中单元格跨行数
      let tdActiveRowspan = Number($tdActive.attr('rowspan')) ? Number($tdActive.attr('rowspan')) : 1;
      //当前选中单元格跨列数
      let tdActiveColspan = Number($tdActive.attr('colspan')) ? Number($tdActive.attr('colspan')) : 1;

      //当前选中单元格行
      let $tdActiveParentTr = $tdActive.parents('tr');
      //当前选中单元格行索引
      let tdActiveParentTrIndex = $tdActiveParentTr.index();

      //当前选单元格下一行
      let $tdActiveParentNextTr = $tdActiveParentTr.next();
      //当前选单元格下一行索引
      let tdActiveParentNextTrIndex = $tdActiveParentNextTr.index();

      //表格第一行
      let $firstTr = $('.table-report').find('tr').eq(0);
      switch (name) {
        case 'rowspanLenth':
          //相同索引的TD是否进行过合并
          let sameTdrowspan = $tdActiveParentNextTr.find('td').eq(tdActiveIndex).attr('rowspan');
          let sameTdcolspan = $tdActiveParentNextTr.find('td').eq(tdActiveIndex).attr('colspan');
          if (Number(tdActiveRowspan) < this.model.rowspanLenth) {
            let trLenth = $('.table-report').find('tr').length;
            if ((sameTdrowspan && Number(sameTdrowspan) > 1) || (sameTdcolspan && Number(sameTdcolspan) > 1)) {
              //限制隔行跨列时当前下一行的TD不能存在合并属性
              this.$message.error('隔行单元格已经存在合并，请先将其还原再进行操作！');
            } else if (this.model.rowspanLenth > trLenth - tdActiveParentNextTrIndex) {
              this.$message.error('跨行数已经达到最大值，请插入表格行再继续操作！');
            } else {
              $tdActive.attr('rowspan', this.model.rowspanLenth);
              if (tdActiveColspan > 1) {
                //对跨行的TR进行删除Td操作，删除td的数量由跨列数决定
                for (let index = 0; index < tdActiveColspan; index++) {
                  $('.table-report')
                    .find('tr')
                    .eq(tdActiveParentTrIndex + tdActiveRowspan)
                    .find('td')
                    .eq(tdActiveIndex + index)
                    .remove();
                }
              } else {
                //通过索引找到当前检验报告组件的TR，再通过索引找到TD，然后将其移除
                console.log(tdActiveParentTrIndex);
                $('.table-report')
                  .find('tr')
                  .eq(tdActiveParentTrIndex + tdActiveRowspan)
                  .find('td')
                  .eq(tdActiveIndex)
                  .remove();
              }
            }
          } else {
            if (this.model[name] >= 1) {
              $tdActive.attr('rowspan', this.model.rowspanLenth);
              if (tdActiveColspan > 1) {
                //对跨行的TR进行添加Td操作，添加td的数量由跨列数决定
                for (let index = 0; index < tdActiveColspan; index++) {
                  $('.table-report')
                    .find('tr')
                    .eq(tdActiveParentTrIndex + this.model.rowspanLenth)
                    .find('td')
                    .eq(tdActiveIndex + index)
                    .after('<td></td>');
                }
              } else {
                //通过找到TR行索引再添加TD
                $('.table-report')
                  .find('tr')
                  .eq(tdActiveParentTrIndex + this.model.rowspanLenth)
                  .find('td')
                  .eq(tdActiveIndex)
                  .after('<td></td>');
              }
            }
          }
          break;
        case 'colspanLenth':
          let nextcolspan = $tdActive.next().attr('colspan');
          let maxcolspan = 0;
          //获取当前选中单元格的下一行所有td数量，包括夸列td，用做最大跨列数
          $firstTr.find('td').each((index, td) => {
            var colspan = Number($(td).attr('colspan'));
            maxcolspan += colspan ? colspan : 1;
          });
          if (Number(tdActiveColspan) < this.model.colspanLenth) {
            if (nextcolspan && Number(nextcolspan) > 1) {
              this.$message.error('右侧单元格已经存在合并，请先将其还原再进行操作！');
            } else if (this.model.colspanLenth > maxcolspan) {
              this.$message.error('跨列数已经达到最大值，请插入表格列再继续操作！');
            } else if (Number(tdActiveRowspan) > 1) {
              this.$message.error('当前单元格已经存在跨行，请先将其还原再进行操作！');
            } else {
              $tdActive.attr('colspan', this.model.colspanLenth);
              if (tdActiveRowspan > 1) {
                //移除当前行Td
                // $tdActive.next().remove();
                $tdActiveParentTr.find('td').each((index, td) => {
                  if (index > 0 && index < this.model.colspanLenth) $(td).remove();
                });
                //跨行数表示需要对多少个TR进行删除TD操作
                for (let index = 1; index < tdActiveRowspan; index++) {
                  $('.table-report')
                    .find('tr')
                    .eq(tdActiveParentTrIndex + index)
                    .find('td')
                    .eq(tdActiveIndex)
                    .remove();
                }
              } else {
                // $tdActive.next().remove();
                $tdActiveParentTr.find('td').each((index, td) => {
                  if (index > 0 && index < this.model.colspanLenth) $(td).remove();
                });
              }
            }
          } else {
            if (this.model[name] >= 1) {
              $tdActive.attr('colspan', this.model.colspanLenth);
              if (tdActiveRowspan > 1) {
                //当前选中TD后面增加TD
                $tdActive.after('<td></td>');
                //跨行数表示需要对多少个TR进行增加TD操作
                for (let index = 1; index < tdActiveRowspan; index++) {
                  $('.table-report')
                    .find('tr')
                    .eq(tdActiveParentTrIndex + index)
                    .find('td')
                    .eq(tdActiveIndex)
                    .after('<td></td>');
                }
              } else {
                //当前选中TD后面增加TD
                $tdActive.after('<td></td>');
              }
            }
          }
          break;
        default:
          break;
      }
    },

    /**
     * 当前选中TD后插入行
     */
    addReportTr() {
      //当前选中单元格
      let $tdActive = $('.table-report').find('td.tdActive');
      //当前选中单元格跨行数
      let tdActiveRowspan = Number($tdActive.attr('rowspan')) ? Number($tdActive.attr('rowspan')) : 1;

      //当前选中单元格行
      let $tdActiveParentTr = $tdActive.parents('tr');
      //当前选中单元格行索引
      let tdActiveParentTrIndex = $tdActiveParentTr.index();

      let appendTdLenth = 0;
      //计算当前选中的tr有多少个td，再添加tr
      $tdActiveParentTr.find('td').each((index, td) => {
        var colspan = $(td).attr('colspan');
        colspan = Number(colspan) ? Number(colspan) : 1;
        appendTdLenth += colspan;
      });
      let tdStr = ``;
      for (let index = 0; index < appendTdLenth; index++) {
        tdStr += `<td></td>`;
      }

      if (tdActiveRowspan > 1) {
        $('.table-report')
          .find('tr')
          .eq(tdActiveParentTrIndex + tdActiveRowspan - 1)
          .after(`<tr>${tdStr}</tr>`);
      } else {
        $tdActiveParentTr.after(`<tr>${tdStr}</tr>`);
      }
    },
    /**
     * 删除表格当前行
     */
    deleteReportTr() {
      //当前选中单元格
      let $tdActive = $('.table-report').find('td.tdActive');
      //当前选中单元格跨行数
      let tdActiveRowspan = Number($tdActive.attr('rowspan')) ? Number($tdActive.attr('rowspan')) : 1;

      //当前选中单元格行
      let $tdActiveParentTr = $tdActive.parents('tr');
      //当前选中单元格行索引
      let tdActiveParentTrIndex = $tdActiveParentTr.index();

      if (tdActiveRowspan > 1) {
        this.model.rowspanLenth = --this.model.rowspanLenth;
        $tdActive.attr('rowspan', tdActiveRowspan - 1);
        $dragItem
          .find('tr')
          .eq(tdActiveParentTrIndex + tdActiveRowspan - 1)
          .remove();
      } else {
        $tdActiveParentTr.remove();
      }
    },
    /**
     * 最后一列后插入列
     */
    addReportTd() {
      //当前选中单元格
      let $tdActive = $('.table-report').find('td.tdActive');
      //当前选中单元格索引
      let tdActiveIndex = $tdActive.index();
      //当前选中单元格行
      let $tdActiveParentTr = $tdActive.parents('tr');
      //当前选中单元格行索引
      let tdActiveParentTrIndex = $tdActiveParentTr.index();
      let $trs = $('.table-report').find('tbody tr');
      let tdActiveIndexAndColspan = 0;
      for (let n = 0; n < tdActiveIndex + 1; n++) {
        tdActiveIndexAndColspan = $($trs[tdActiveParentTrIndex]).find('td').eq(n).attr('colspan')
          ? Number($($trs[tdActiveParentTrIndex]).find('td').eq(n).attr('colspan')) + Number(tdActiveIndexAndColspan)
          : 1 + Number(tdActiveIndexAndColspan);
      }
      console.log(tdActiveIndexAndColspan);
      for (let i = 0; i < $trs.length; i++) {
        if (i != tdActiveParentTrIndex) {
          let $tds = $($trs[i]).find('td');
          let tdColspan = 0;
          for (let j = 0; j < $tds.length; j++) {
            tdColspan = $($tds[j]).attr('colspan') ? Number($($tds[j]).attr('colspan')) + Number(tdColspan) : 1 + Number(tdColspan);
            console.log(i, j, tdColspan, tdActiveIndexAndColspan);
            if (Number(tdColspan) == tdActiveIndexAndColspan) {
              $($tds[j]).after('<td></td>');
              break;
            } else if (Number(tdColspan) > tdActiveIndexAndColspan) {
              $($tds[j]).attr('colspan', Number($($tds[j]).attr('colspan')) + 1);
              break;
            }
          }
        } else {
          $tdActive.after('<td></td>');
        }
      }
    },
    /**
     * 删除列
     */
    deleteReportTd() {
      //当前选中单元格
      let $tdActive = $('.table-report').find('td.tdActive');
      //当前选中单元格索引
      let tdActiveIndex = $tdActive.index();
      //当前选中单元格行
      let $tdActiveParentTr = $tdActive.parents('tr');
      //当前选中单元格行索引
      let tdActiveParentTrIndex = $tdActiveParentTr.index();
      let $trs = $('.table-report').find('tbody tr');
      let tdActiveIndexAndColspan = 0;
      for (let n = 0; n < tdActiveIndex + 1; n++) {
        tdActiveIndexAndColspan = $($trs[tdActiveParentTrIndex]).find('td').eq(n).attr('colspan')
          ? Number($($trs[tdActiveParentTrIndex]).find('td').eq(0).attr('colspan')) + Number(tdActiveIndexAndColspan)
          : 1 + Number(tdActiveIndexAndColspan);
      }
      for (let i = 0; i < $trs.length; i++) {
        if (i != tdActiveParentTrIndex) {
          let $tds = $($trs[i]).find('td');
          let tdColspan = 0;
          for (let j = 0; j < $tds.length; j++) {
            tdColspan = $($tds[j]).attr('colspan') ? Number($($tds[j]).attr('colspan')) + Number(tdColspan) : 1 + Number(tdColspan);
            if (Number(tdColspan) == tdActiveIndexAndColspan) {
              if ($($tds[j]).attr('colspan') && Number($($tds[j]).attr('colspan')) > 1) {
                $($tds[j]).attr('colspan', Number($($tds[j]).attr('colspan')) - 1);
              } else {
                $($tds[j]).remove();
              }
              break;
            } else if (Number(tdColspan) > tdActiveIndexAndColspan) {
              $($tds[j]).attr('colspan', Number($($tds[j]).attr('colspan')) - 1);
              break;
            }
          }
        } else {
          $tdActive.remove();
        }
      }
    }
  }
};
</script>
<style lang="scss">
.templateUi {
  // 改变element-ui深层元素
  ::v-deep .el-card__header {
    padding: 6px 8px !important;
  }

  .el-card__body {
    padding: 0;
  }

  // 画布上方操作栏
  .designer-btns {
    display: flex;
    justify-content: space-between;
    border-bottom: 2px solid #dedede;

    ul {
      list-style: none;
      display: flex;
      padding: 0;
      margin: 0;

      li {
        width: 70px;
        height: 70px;
        padding: 0 10px;
        text-align: center;
        font-size: 15px;
        cursor: pointer;

        p {
          margin-bottom: 0;
          margin-top: -5px;
          font-size: 12px;
          font-weight: 400;
        }
      }

      .bg-blue {
        display: flex;
        align-items: center;
      }
    }
  }

  // 中间工站信息
  .designer-description {
    display: flex;
    padding: 5px;
    align-items: center;
    font-size: 16px;
  }

  .designer-box {
    display: flex;
    height: calc(100vh - 238px);
    .designer-div {
      // border: 2px solid #648BA4;
      height: calc(100vh - 270px);
      overflow: auto;
      padding: 10px;
      .table-report {
        width: 100%;
        text-align: center;
        font-size: 12px;
        color: #333;
        border-collapse: collapse;
        border-color: #999;
        td {
          height: 30px;
          padding-left: 15px;
          padding-right: 15px;
          text-align: center;
          /* min-width: 50px; */
        }
        td.tdActive {
          /* border: 1px solid #0037ff; */
          background: #f7ee9c;
        }
        ::v-deep .input-control {
          padding: 1px;
          margin: 2px;
          width: 100%;
          height: auto;
          line-height: 25px;
          font-size: 12px;
          font-size: smaller;
          text-align: center;
        }
      }
    }
  }
  // 侧边工站基本信息栏
  .nav-tab {
    height: calc(100vh - 273px);

    .el-tabs__item {
      padding: 0;
      width: 90px;
      text-align: center;
    }

    .el-form--label-top .el-form-item__label {
      padding: 0;
    }

    .el-tab-pane {
      padding: 0 5px;
    }

    .avue-form__menu {
      display: none;
    }

    .border-title {
      border-left: 5px solid #5a93bb;
      border-bottom: 2px dashed #ccc;
      font-weight: 700;
      padding-left: 5px;
      font-size: 15px;
    }

    .addRequestBtn {
      width: 100%;
      margin: 10px 0;
    }

    .check-item-content {
      width: 95%;
      margin: 10px;

      ::v-deep .clearfix {
        font-size: 15px;
        font-weight: bold;
      }

      .isCheck-item-content {
        word-break: break-all;
        padding: 5px 8px;
      }
    }

    .el-form {
      .el-select {
        width: 100%;
      }

      .el-form-item {
        margin-bottom: 0;
      }
    }

    .request-item-content {
      margin-bottom: 10px;

      .el-card__body {
        padding: 5px 5px;

        .el-form-item {
          .el-input-number {
            width: 100%;
          }
        }
      }
    }

    .el-button {
      width: 100%;
    }

    .el-tabs__header {
      margin: 0;
    }

    .el-form-item__content {
      line-height: 32px;
    }

    .el-input-number {
      width: 100%;
    }
  }
}
</style>
